iT邦幫忙

2021 iThome 鐵人賽

DAY 19
0
Software Development

iOS 學習筆記系列 第 19

Day19 Combine 06 - Operators 類型介紹 : 過濾操作符

  • 分享至 

  • xImage
  •  

filter

filter 只會讓滿足條件的值通過,filter接受一個閉包作為引數,該閉包返回一個Bool型別的值,只有結果為true的資料才會被儲存下來

[1, 6, 15, 22].publisher
    .filter { value in
        value > 10
    }
    .sink(receiveCompletion: { _ in
        print("finished")
    }, receiveValue: { value in
        print(value)
    })
/*印出 
15
22
finished
*/

compactMap

compactMapmap的功能類似,只是會自動過濾掉空的元素,它的引數中的閉包支援返回一個可選型別的引數,因此,我們可以把傳進來的資料直接返回,就這麼簡單的一個操作就實現了空值過濾

["1", nil, "2", nil, "3"].publisher
    .compactMap { value -> Int? in
        guard let v = value else {
            return nil
        }
        return Int(v)
    }
    .sink(receiveCompletion: { _ in
        print("finished")
    }, receiveValue: { value in
        print(value)
    })
/*印出 
1
2
3
finished
*/

removeDuplicates

removeDuplicates 過濾掉連續的重複值

[1, 1, 1, 2, 2, 1, 2, 3].publisher
    .removeDuplicates()
    .sink(receiveCompletion: { _ in
        print("finished")
    }, receiveValue: { value in
        print(value)
    })
/*印出 
1
2
1
2
3
finished
*/

replaceEmpty/replaceNil/replaceError

  • 如果上游Publisher 是個空的數據流,replaceEmpty會發送指定的值

    Empty<Int, Never>()
        .replaceEmpty(with: 1)
        .sink(receiveCompletion: { _ in
            print("finished")
        }, receiveValue: { value in
            print(value)
        })
    /*印出 
    1
    finished
    */
    

    空的數據流:在收到finish事件前,從來沒有收到任何資料

    Empty:一個只發出完成事件的Publisher

  • 將收到的nil轉換為給定的值

    [1, nil, 3].publisher
    		.replaceNil(with: -1)
    		.map { $0! }
    		.sink(receiveCompletion: { _ in
    				print("finished")
    		}, receiveValue: { value in
    				print(value)
     		})
    /*印出 
    1
    -1
    3
    finished
    */
    
  • 如果上游Publisher 因錯誤而終止,replaceError會發送指定的值

    enum MyError: Error {
      case failed
    }
    
    var subject = PassthroughSubject<Int, Error>()
    
    subject
      .replaceError(with: 0)
      .sink(receiveCompletion: { completion in
        print(completion)
      }, receiveValue: { int in
        print(int)
      })
    
    subject.send(1)
    subject.send(2)
    subject.send(completion: .failure(MyError.failed))
    

上一篇
Day18 Combine 05 - Operators 類型介紹 : 轉換操作符
下一篇
Day20 Combine 07 - Operators 其他常用操作符
系列文
iOS 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言